﻿using IdentityModel.Client;
using LivestreamE_Commerce.IService.Ids4;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace LivestreamE_Commerce.Service.Ids4
{
    public class Idis4Service : IIds4Service
    {
        private IConfiguration configuration;
        public Idis4Service(IConfiguration _configuration) 
        {
            configuration = _configuration;
        }

        public async Task<string> GetIdsTokeAsync(string LoginName, string Loginpwd)
        {
            var client = new HttpClient();
            var idsTokenUrl = configuration.GetSection("AuthServer:Authority").Value;//ids4访问url地址
            var AppClientId = configuration.GetSection("AuthServer:AppClientId").Value;//Ids4访问
            var AppClientSecret = configuration.GetSection("AuthServer:AppClientSecret").Value;//ids4访问密码
            var disco = client.GetDiscoveryDocumentAsync(idsTokenUrl);

            var tokenResponse = await client.RequestPasswordTokenAsync(
                new PasswordTokenRequest
                {
                    Address = disco.Result.TokenEndpoint,
                    ClientId = AppClientId,
                    ClientSecret = AppClientSecret,
                    UserName = LoginName,
                    Password = Loginpwd
                });
            if (tokenResponse.IsError)
            {
                return string.Empty;
            }
            return tokenResponse.AccessToken;
        }
    }
}
